﻿using System;
using System.IO;
using System.Linq;
using System.Xml.Serialization;

namespace T68Control.Procdure
{
    internal enum CurrentEnum
    {
        /// <summary>
        /// 四块板子
        /// </summary>
        AllHigh1,

        AllMid1,
        AllLow1,
        AllQG1,
        AllQG2,

        /// <summary>
        /// PB3,PB2
        /// </summary>
        SubHigh1,

        SubMid1,
        SubLow1,
        SubQG1,
        SubQG2,
    }

    [XmlRoot("系统配置")]
    [Serializable]
    public class Config
    {
        private static string file = "config.xml";
        private static string dir = "config_backup";

        [XmlElement("工装只能测试一套")]
        public bool IsOneProduct { get; set; }

        [XmlElement("高压电源串口")]
        public string RU18Port { get; set; }

        [XmlElement("万用表串口")]
        public string DM3058EPort { get; set; }

        [XmlElement("IV3003T串口")]
        public string IV3003TPort { get; set; }

        /// <summary>
        /// 继电器模块端口
        /// </summary>
        [XmlElement("继电器模块端口")]
        public string PQW_IO_Port { get; set; }

        [XmlElement("SN码长度")]
        public int SNLength { get; set; }

        [XmlElement("测试配置文件路径")]
        public string TestFilePath { get; set; }

        [XmlElement("视觉文件路径")]
        public string VisionFilePath { get; set; }

        [XmlElement("NG图片文件路径")]
        public string FailImagePath { get; set; }

        [XmlElement("输出报告路径")]
        public string ReportDirectory { get; set; }

        [XmlElement("输出报告备份路径")]
        public string ReportBackupDirectory { get; set; }

        [XmlElement("高流电源表电压")]
        public double RU_18_10001Voltage { get; set; }

        [XmlElement("高流电源表电流")]
        public double RU_18_10001Current { get; set; }

        [XmlElement("IV3003T通道1电压")]
        public int IV3003TCH1Voltage { get; set; }

        [XmlElement("IV3003T通道1电流")]
        public double IV3003TCH1Current { get; set; }

        [XmlElement("IV3003T通道2电压")]
        public int IV3003TCH2Voltage { get; set; }

        [XmlElement("IV3003T通道2电流")]
        public double IV3003TCH2Current { get; set; }

        [XmlElement("IV3003T通道3电压")]
        public int IV3003TCH3Voltage { get; set; }

        [XmlElement("IV3003T通道3电流")]
        public double IV3003TCH3Current { get; set; }

        public static Config Load()
        {
            if (!File.Exists(file))
            {
                Config c = new Config
                {
                    IsOneProduct = false,
                    DM3058EPort = "COM5",
                    IV3003TPort = "COM6",
                    RU18Port = "COM7",
                    PQW_IO_Port = "COM8",
                    SNLength = 1,
                    TestFilePath = "do_config.xlsx",
                    ReportDirectory = @"D:\Output",
                    ReportBackupDirectory = @"E:\backup\report",
                    FailImagePath = @"E:\fail_images",
                    VisionFilePath = @"D:\vision_projects\T68Control.sol",
                    RU_18_10001Voltage = 4.2,
                    RU_18_10001Current = 4.5,
                    IV3003TCH1Voltage = 5,
                    IV3003TCH2Voltage = 5,
                    IV3003TCH3Voltage = 5,
                    IV3003TCH1Current = 1,
                    IV3003TCH2Current = 1,
                    IV3003TCH3Current = 1,
                };

                Save(c);
                DeleteOldFiles(dir);
                return c;
            }
            else
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Config));

                TextReader reader = new StreamReader(file);
                // 初始化默认值

                var obj = serializer.Deserialize(reader);
                reader.Close();
                return obj as Config;
            }
        }

        public static void Save(Config config)
        {
            if (config is null)
            {
                throw new ArgumentNullException("参数错误");
            }
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            var temp = file.Length - 4;
            string tmp =
                $"./{dir}/config-{file.Substring(0, temp)}{DateTime.Now.ToString("yyyyMMdd")}.xml";
            if (File.Exists(tmp))
            {
                File.Delete(tmp);
            }

            XmlSerializer serializer = new XmlSerializer(typeof(Config));
            TextWriter writer = new StreamWriter(tmp);
            serializer.Serialize(writer, config);
            writer.Close();

            if (File.Exists(file))
            {
                File.Delete(file);
            }
            File.Copy(tmp, file);
        }

        /// <summary>
        /// 保留最新14次的备份文件
        /// </summary>
        /// <param name="folderPath"></param>
        private static void DeleteOldFiles(string folderPath)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
            FileInfo[] files = directoryInfo.GetFiles();

            // 按修改时间从最晚到最早进行排序
            var sortedFiles = files.OrderByDescending(f => f.LastWriteTime);
            var fi = sortedFiles.First().LastWriteTime;

            // 输出排序后的文件列表
            foreach (FileInfo file in sortedFiles)
            {
                TimeSpan age = fi - file.LastWriteTime;
                if (age.TotalDays > 14)
                {
                    Console.WriteLine(file.LastWriteTime);
                    file.Delete();
                }
            }
        }
    }
}